package caseManagerBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.ReturnJson;
import models.SqlReturnModel;
import tools.DDAlert;
import tools.Http;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yangxianming on 2018/12/20.
 * 这个方法调用代码用例，如python 或 java编写的测试用例
 * caseId=12   caseId=12,23,43
 */
public class RunOtherCase implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();
        //解析请求数据，拆分一组caseId
        String caseIdStr = request.getParameter("caseId");
        String back302 = request.getParameter("back302");
        String domain302 = request.getParameter("domain302");
        String needAlert = request.getParameter("needAlert");
        String[] caseArr = caseIdStr.split(",");
        ArrayList<String> caseArrayList = new ArrayList<String>();
        Collections.addAll(caseArrayList, caseArr);
        String caseStr = "(";
        for (int i = 0; i < caseArr.length; i++){
            try {
                Integer.valueOf(caseArr[i]);
            }catch (Exception e){
                System.out.println("忽略caseid非数字的元素");
                continue;
            }
            caseStr = caseStr + "\"" + caseArr[i] + "\"";
            if (i < (caseArr.length-1)){
                caseStr = caseStr + ",";
            }
        }
        caseStr = caseStr + ")";
        //组装sql,查询数据库获取用例脚本
        String where = "id in " + caseStr;
        SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
        SqlReturnModel sqlReturnModel = sqlDispatch.select("`id`,`data`,`type`", "testcase", where, "createtime");
        JSONArray executeList = new JSONArray();
        for (int i=0; i<caseArrayList.size(); i++){
            executeList.add(null);
        }
        boolean isPython = false;

        //生成批次号，并预插入test report表
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String logName = sdf1.format(new Date());
        Random random = new Random();
        String s = String.format("%04d", random.nextInt(9999));
        String batchNo = logName + "S" + s;

        //组装执行语句 组装预插入语句
        //INSERT INTO `testserver`.`testreport` (`caseId`, `batchnumber`, `type`) VALUES ('28', 'batch', '3');
        String sqlWord = "INSERT INTO `testreport` (`caseId`, `batchnumber`, `type`, `result`) VALUES ";
        for (ArrayList<String> el: sqlReturnModel.getSelectReturnData()){
            String caseId = el.get(0);
            int caseIdIndex = caseArrayList.indexOf(caseId);
            String caseName = JSON.parseObject(el.get(1)).getString("caseName");
            String type = el.get(2);
            if (Objects.equals("3", type)){
                //判断类型
                isPython = true;
                JSONObject oneTask = new JSONObject();
                oneTask.put("caseId", caseId);
                oneTask.put("caseName", caseName);
                oneTask.put("params", "");
                oneTask.put("batchNo", batchNo);
                executeList.set(caseIdIndex, oneTask);
            }
            //组装与插入sql语句
            sqlWord += "('" + caseId + "', '" + batchNo + "', '" + type + "', '0'),";
        }
        //执行前不在预插入空的记录，和ui测试保持一致
//        sqlWord = sqlWord.substring(0, sqlWord.length()-1);
//        sqlDispatch.insert(sqlWord);

        //获得节点服务器域名
        String nodeDomain = myConfig.getPropertiesConfig().getProperties().getProperty("nodeServer");

        //给节点服务器发送执行请求
        Http http = new Http();
        //判断是什么脚本
        if (isPython){
            http.sendRequest("post", null, "http://"+nodeDomain+"/external/pythonExecter", executeList.toJSONString());
        }

        //组装返回值
        String reportPage = domain302;
        reportPage = reportPage + "/html/caseReport.html?batchNo=" + batchNo;
        JSONObject returnInfo = new JSONObject();
        returnInfo.put("batchNo", batchNo);
        returnInfo.put("reportPage", reportPage);
        if (Objects.equals(back302, "1")){
            returnInfo.put("302Page", reportPage);
        }
        //钉钉中通知
        if (Objects.equals(needAlert, "1")){
            String[] message = {"触发了一次自动化测试", "[mu]点击链接将展示测试结果", "", reportPage};
            DDAlert ddAlert = new DDAlert();
            ddAlert.send("link", "url3", message, "13564324375");
        }

        returnJson.setApiStatus(1);
        returnJson.setResult(returnInfo);
        return returnJson.toString();
    }
}
